package com.zk.lib_service

import android.app.ActivityManager
import android.content.*
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.annotation.RequiresApi
import com.gc.logger.LogUtils
import com.zk.lib_service.service.*
import java.util.*

/**
 * 1.service 启动与关闭
 *  context.startService
 *  测试home键  荣耀80GT 15:15:57.403 启动服务  15:17:01.902自动结束，在后台运行64秒
 *  测试back键     荣耀80GT  15:18:04.661  15:19:13.459 自动结束，在后台运行64秒
 *  测试锁屏        荣耀80GT    15:22:40.869 15:23:50.057 自动结束，在后台运行64秒
 *
 *  onStartCommand START_STICKY 无任何作用，切换到后台会被杀死，几时回到不会重新起来
 *  普通服务切换到后台，一段时间之后会被杀死，应用切换回来也无法启动
 *
 *  在后台启动startservice服务,应用在挂起状态后，不允许启动后台服务 大概一分钟之后，或者是在服务的自动ondestory中，启动服务，这时也会触发异常
 *  android.app.BackgroundServiceStartNotAllowedException: Not allowed to start service Intent
 *
 *  startForeground()
 *  java.lang.SecurityException: Permission Denial: startForeground from pid=27815, uid=10180 requires android.permission.FOREGROUND_SERVICE
 *
 *  android.app.RemoteServiceException: Bad notification for startForeground
 *
 *  前台应用继承importance=100，切换到后台importance=300，使用前台服务，进程importance=125
 *
 * bindservice  切换到后台 importance=400，14:57:38
 *
 * 不能unbind一个未绑定的通知，会发生异常
 *
 *  绑定与startfore都不会自动关闭service，如何模拟设备后台杀应用
 *
 *
 *
 *
 */
object ServiceManager {
    private val connectionMap = WeakHashMap<Context, ServiceConnection>()
    fun startService(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager startService ")
        context.startService(Intent(context.applicationContext, MusicPlayerService::class.java))
    }

    fun stopService(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager closeService ")
        context.stopService(Intent(context, MusicPlayerService::class.java))
    }

    fun startService2(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager startService ")
        context.startService(Intent(context, MusicPlayerAutoRestartService::class.java))
    }

    fun stopService2(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager closeService ")
        context.stopService(Intent(context, MusicPlayerAutoRestartService::class.java))
    }

    fun getRunServiceInfos(context: Context) {
        var mActivityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var runningServices = mActivityManager.getRunningServices(20)
        LogUtils.e("aaaaaaaaaaaa", "poccess id =${android.os.Process.myPid()}")
        if (runningServices.isNotEmpty()) {
            for (runServiceInfo in runningServices) {
                var pid = runServiceInfo.pid
                var className = runServiceInfo.service.className
                var clientCount = runServiceInfo.clientCount
                var foreground = runServiceInfo.foreground
                var activeSince = runServiceInfo.activeSince
                var flags = runServiceInfo.flags
                var lastActivityTime = runServiceInfo.lastActivityTime
                var started = runServiceInfo.started
                var restarting = runServiceInfo.restarting
                LogUtils.e("aaaaaaa",
                    "Service className=$className pid=$pid clientCount=$clientCount foreground=$foreground " +
                            "activeSince=$activeSince flags=$flags lastActivityTime=$lastActivityTime started=$started restarting=$restarting")
            }
        } else {
            LogUtils.e("aaaaaaaaaaaa", "无运行的service")
        }
        var runningAppProcesses = mActivityManager.runningAppProcesses
        if(runningAppProcesses.isNotEmpty()){
            for(info in runningAppProcesses){
                var pid = info.pid
                var importance = info.importance
                var processName = info.processName
                LogUtils.e("aaaaaaa",
                    "Processes processName=$processName pid=$pid importance=$importance ")
            }
        }




    }

    fun startServiceOnBackgroud(mContext: Context) {
        val home = Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        home.addCategory(Intent.CATEGORY_HOME)
        mContext.startActivity(home)

        var handler = Handler(Looper.getMainLooper())
        handler.postDelayed(Runnable {
            startService(mContext)
        }, 150000)
    }


    fun startForeService(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager startService ")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(Intent(context.applicationContext, ForegroundAutoRestartService::class.java))
        }
    }

    fun stopForeService(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager closeService ")
        context.stopService(Intent(context, ForegroundAutoRestartService::class.java))
    }

    fun startForeService2(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager startService ")
        context.startService(Intent(context, ForegroundAutoRestartService::class.java))
    }



    fun startBindService(context: Context):Context {
        LogUtils.e("aaaaaaaaa", "ServiceManager bindService ")
//        val contextWrapper = ContextWrapper(context)
        val intent = Intent(context, MusicBinderService::class.java)
        var connection=connectionMap[context]?:getServiceConnection()
        if(context.bindService(intent,connection,Context.BIND_AUTO_CREATE)){
            connectionMap[context]=connection
        }else{
            LogUtils.e("aaaaaaaaa", "ServiceManager bindService 失败")
        }
        return context

    }

    fun startForeBindService(context: Context):Context {
        LogUtils.e("aaaaaaaaa", "ServiceManager forebindService ")
        val contextWrapper = ContextWrapper(context)
        val intent = Intent(contextWrapper, ForegroundBinderService::class.java)
        var connection=getServiceConnection()
        if(context.bindService(intent,connection,Context.BIND_AUTO_CREATE)){
            connectionMap[contextWrapper]=connection
        }else{
            LogUtils.e("aaaaaaaaa", "ServiceManager forebindService 失败")
        }
        return contextWrapper

    }

    fun stopUnBindService(context: Context) {
        LogUtils.e("aaaaaaaaa", "ServiceManager unbindService ")
        connectionMap[context]?.apply {
            context.unbindService(this)
        }


    }
    fun getServiceConnection():ServiceConnection{
        return object :ServiceConnection{
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                try {
                    if (service is MusicServiceBinder) {
                        LogUtils.e("aaaaaaaaaaaaa","onServiceConnected service hashcode=${service.hashCode()}")
                    }
                } catch (ex: Exception) {
                    ex.printStackTrace()
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                LogUtils.e("aaaaaaaaaaaaa","onServiceDisconnected")
            }

        }
    }

    fun startAndForeBindService(context: Context):Context {
        LogUtils.e("aaaaaaaaa", "ServiceManager startService ")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(Intent(context.applicationContext, ForegroundBinderService::class.java))
        }

        LogUtils.e("aaaaaaaaa", "ServiceManager forebindService ")
        val contextWrapper = ContextWrapper(context)
        val intent = Intent(contextWrapper, ForegroundBinderService::class.java)
        var connection=getServiceConnection()
        if(context.bindService(intent,connection,Context.BIND_AUTO_CREATE)){
            connectionMap[contextWrapper]=connection
        }else{
            LogUtils.e("aaaaaaaaa", "ServiceManager forebindService 失败")
        }
        return contextWrapper
    }
    fun stopAndForeBindService(context: Context){
        LogUtils.e("aaaaaaaaa", "ServiceManager closeService ")
        context.stopService(Intent(context, ForegroundBinderService::class.java))
    }
//    private val serviceConnection = object : ServiceConnection {
//        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
//            try {
//                if (service is MusicServiceBinder) {
//                    binder=service
//                    Log.e("aaaaaaaaaaaaa","onServiceConnected service hashcode=${service.hashCode()}")
//                }
//            } catch (ex: Exception) {
//                ex.printStackTrace()
//            }
//        }
//
//        override fun onServiceDisconnected(name: ComponentName?) {
//            Log.e("aaaaaaaaaaaaa","onServiceDisconnected")
//        }
//    }

}